#include "AsioIOServicePool.h"

AsioIOServicePool::~AsioIOServicePool()
{
	std::cout << "AsioIOServicePool::~AsioIOServicePool()" << std::endl;
}

boost::asio::io_context& AsioIOServicePool::GetIOService()
{
	auto& context = _ioServices[_nextIOService++];
	if (_nextIOService == _ioServices.size())
	{
		_nextIOService = 0;
	}
	return context;
}

void AsioIOServicePool::Stop()
{
	for (auto& work : _works)
	{
		work->get_io_context().stop();
		work.reset();
	}
	for (auto& t : _threads)
	{
		t.join();
	}
}

AsioIOServicePool::AsioIOServicePool(size_t poolSize)
	:_ioServices(poolSize)
	,_works(poolSize)
	,_nextIOService(0)
{
	for (int i = 0; i < poolSize; i++)
	{
		_works[i] = std::unique_ptr<Work>(new Work(_ioServices[i]));
	}

	for (int i = 0; i < poolSize; i++)
	{
		_threads.emplace_back([this,i]() {
			_ioServices[i].run();
			});
	}
}
